<?php
namespace AuctionCore\FoursStore;
/**
 * 拍卖管理列表
 * @author shijiabng
 */
class AuctionList{
	private $_car_id = null;
	public $count_sql = null;
	public $order_by;
	public $cols = null;
    public $subQuery = null;

	public function __costruct(){
	}

  /**
  * 获得品牌、车系、车型信息
  * @param int $id id
  * @param string $type 类型(mbrand,brand,series,model)
  * @return array
  */
  private function get_brand_by_name($name,$type='brand'){
      $condition['name'] = array('like','%'.$name.'%');
      return M('car_'.$type)->field('brand_id')->where($condition)->getField('brand_id',true);
  }

   /**
     * 统计待上拍数量
     */
    private function bidUp($params){        
        $where['o.status'] = array('in', array('1','2'));
        $where['c.car_status'] = array('in', array('4','7'));
        $where['_logic'] = 'OR';
        $map['_complex'] = $where;
        if(!empty($params)){
            $map = array_merge($params,$map);
        }
        $sum = $this->getCount($map);
        return $sum;
    }
    /**
     * 统计拍卖中数量
     */
    private function bidMiddle($params){        
        $map['o.status'] = array('in', array('3','301','4'));
        if(!empty($params)){
            $map = array_merge($params,$map);
        }
        $sum = $this->getCount($map);
        return $sum;
    }
    /**
     * 统计拍卖总数量
     */
    private function bidAll($params){        
        $map1['o.status'] = array('in', array('3','301','4'));
        $map = array_merge($params,$map);
        if(!empty($params)){
            $map = array_merge($params,$map);
        }
        $sum = $this->getCount($map);
        return $sum;
    }


	/**
	 * 获取拍卖列表
	 */
	public function getList($page,$limit,$params,$fourMap){

        if($params['car_plate']){
            //组装车牌号条件
            $first_code = mb_substr($params['car_plate'], 0,1,'utf-8');
            $last_code = mb_substr($params['car_plate'], 1,6,'utf-8');
            $plate_num = array_flip(C('PLATE_PREFIX'));
            if($plate_num[$first_code]){
              $map['c.plate_prefix'] = array('eq',$plate_num[$first_code]);  
              $params = array_merge($params,$map);
            }       
            if($last_code){
              $map['c.plate_suffix'] = array('eq',$last_code);
              $params = array_merge($params,$map);
            }
        } 
        if($params['car_name']){
            //组装车辆名称条件
            $b_result = $this->get_brand_by_name($params['car_name']);
            if($b_result){
              $map['c.brand_id'] = array('in',$b_result); 
              $params = array_merge($params,$map);
            } else{
              $map['c.brand_id'] = array('eq',0); 
              $params = array_merge($params,$map);
            }       
        }
        //车辆检测时间
        if(!empty($params['start_time']) || !empty($params['end_time'])){
            if (empty($params['start_time'])) {
                $map['c.posttime'] = array("elt", $params['end_time'].' 23:59:59');
            } elseif (empty($params['end_time'])) {
                $map['c.posttime'] = array("egt", $params['start_time'] .' 00:00:00');
            } else {
                $map['c.posttime'] = array(array("egt", $params['start_time'] .' 00:00:00'), array("elt", $params['end_time'] .' 23:59:59'));
            }            
            $params = array_merge($params,$map);            
        }        
        unset($params['start_time']);
        unset($params['end_time']);     
            
        //组装状态条件
        if(!$params['status'])
             $params['status'] = 1;
        $otherMap = array_merge($params,$fourMap);
        unset($otherMap['name']);
        unset($otherMap['start_time']);
        unset($otherMap['end_time']);
        unset($otherMap['car_plate']);
        unset($otherMap['car_name']);
        unset($otherMap['status']);

        switch ($params['status']) {
                    case 1:
                        $where['o.status'] = array('in', array('1','2','3','301','4'));//全部车辆
                        $where['c.car_status'] = array('in', array('4','7'));
                        $where['_logic'] = 'OR';
                        $map['_complex'] = $where;
                        // $sum['total'] = $list_m->getCount($map);
                        $sum['bid_up'] = $this->bidUp($otherMap);
                        $sum['bid_middle'] = $this->bidMiddle($otherMap);
                        break;
                    case '2':
                        $where['o.status'] = array('in', array('1','2'));//待上拍
                        $where['c.car_status'] = array('in', array('4','7'));
                        $where['_logic'] = 'OR';
                        $map['_complex'] = $where;
                        $map = array_merge($map,$otherMap);
                        $sum['bid_up']  = $this->getCount($map);
                        // $sum['total'] = $this->bidAll($otherMap);
                        $sum['bid_middle'] = $this->bidMiddle($otherMap);
                        break;
                    case '3':
                        $map['o.status'] = array('in', array('3','301','4'));//拍卖中
                        $map = array_merge($map,$otherMap);
                        $sum['bid_middle'] = $this->getCount($map);
                        // $sum['total'] = $this->bidAll($otherMap);
                        $sum['bid_up'] = $this->bidUp($otherMap);
                        break;               
        }
        $sum['all'] = $sum['bid_up'] + $sum['bid_middle'];
        $map['suggest_max_price'] = array('gt','0');
        $map['suggest_min_price'] = array('gt','0');
        $params = array_merge($params,$map);
        //添加4s店条件
        $params = array_merge($params,$fourMap);
        unset($params['status']);
        unset($params['car_plate']);
        unset($params['car_name']);  

    	$cols = "c.car_id,c.car_no,c.brand_id,c.series_id,c.model_id,c.car_status,c.reserve_price,c.suggest_min_price,c.suggest_max_price
                    ,c.composite_state,c.accident_level,c.re_auction_type,c.re_auction_reason,c.first_reg_date,c.plate_prefix,c.plate_suffix,o.order_id,o.status,o.remark_reject,co.owner_id,o.bidding_start_time,c.pointer_mileage,co.checker_id,c.posttime,co.comefrom";
        $subQuery = M('cars')->alias('c')
                              ->field($cols)
                              ->join( "LEFT JOIN " .C('DB_PREFIX') . "order o ON c.car_id=o.car_id")
                              ->join( C('DB_PREFIX')."car_owner as co ON co.owner_id=c.owner_id")
                              // ->join(C('DB_PREFIX')."car_pictures as cp ON cp.car_id=o.car_id")
                              ->where($params)->order('order_id') 
                              ->buildSql();

        $list = M()->table($subQuery.' a')->limit($limit)->page($page)->group('car_id')->order('posttime desc')
->select();
        // echo M()->getLastSql();
         
        //数据处理
          $cm = new \AuctionCore\CarResource\CarModel();
          foreach ($list as $key => $val) {
              $list[$key] = $val;
              $brand = $cm->get_model_by_id($val['brand_id'], 'brand');
              $series = $cm->get_model_by_id($val['series_id'], 'series');
              $model = $cm->get_model_by_id($val['model_id']);
              $list[$key]['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
              $list[$key]['reserve_price'] = format_money($val['reserve_price']);
              $list[$key]['suggest_min_price'] = format_money($val['suggest_min_price']);
              $list[$key]['suggest_max_price'] = format_money($val['suggest_max_price']);
              $list[$key]['car_plate_number'] = C('PLATE_PREFIX.' . $val['plate_prefix']) . $val['plate_suffix'];
              if($val['car_status'] == 4 || $val['car_status'] == 7){
                  $list[$key]['car_status_cn'] = C('CAR_STATUS.' . $val['car_status']);
                  // echo $val['car_status'];
              } else{
                  $list[$key]['car_status_cn'] = C('ORDER_STATUS.' . $val['status']);
              }
              //上牌时间
              $date = date($val['first_reg_date']);
              $list[$key]['post_time'] = date('Y',strtotime($date));
              //检测时间
              $overtime = date($val['posttime']);
              $list[$key]['checkdate'] = date('Y-m-d',strtotime($overtime));
              //拍卖时间
              $bidtime = date($val['bidding_start_time']);
              $list[$key]['bidding_time'] = date('Y-m-d',strtotime($bidtime));
              //左前图片
              $list[$key]['left_front45'] = $this->getPics($val['car_id']);
              //卖家信息
              $list[$key]['buger_info'] = $this->carToFours($val['comefrom']);
          }
        $pages = ceil($sum['all']/$limit);
        $result = array(
            'list' => $list,
            'total' => $sum,
            'page' => $pages
        );
        // dump($result);exit;
        return $result;
	}
    /**
     * 获取图片
     * @param  [type] $car_id [description]
     * @return [type]         [description]
     */
    public function getPics($car_id){
        $map['car_id'] = $car_id;
        $map['pic_key'] = array('eq','p_left_front45'); 
        $pics = M('car_pictures')->where($map)->find();
        return $pics['pic_url'];
    }
    /**
     * 获取统计总数
     * @param int $params 条件
     * @return [type] [description]
     */
     public function getCount($params){
        $cols = 'c.car_id';
        // $map = $this->getParams($params);
        $map1['suggest_max_price'] = array('gt',0);
        $map1['suggest_min_price'] = array('gt',0);
        $map = array_merge($map1,$params);
        $subQuery = M('cars')->alias('c')
                              ->field($cols)
                              ->join( "LEFT JOIN ".C('DB_PREFIX') . "order o ON c.car_id=o.car_id")
                              ->join(C('DB_PREFIX')."car_owner as co ON co.owner_id=c.owner_id")
                              // ->join(C('DB_PREFIX')."car_pictures as cp ON cp.car_id=o.car_id")
                              ->where($map)->order('order_id desc')
                              ->buildSql();
        $subQuery1 = M()->table($subQuery.' a')->group('car_id')->buildSql();
        $count = M()->table($subQuery1.' b')->count();
        // echo M()->getlastSql();
        return $count;
    }
        /**
     * 车辆对应来源-获取来源名称
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function carToFours($params){
        $map['from_id'] = array('eq',$params);
        $result = M('come_from')->where($map)->find();
        return $result['from_name'];
    }
	
}